package com.ruoyi.demo.service.impl;




import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.demo.domain.Photo;
import com.ruoyi.demo.respository.UserPhotoRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Date;

@Service
public class PhotoService {

    @Autowired
    private UserPhotoRepository userPhotoRepository;

    public String savePhoto(MultipartFile file, Long userId) {
        // 构建保存路径
        String directoryPath = RuoYiConfig.getProfile() + "/photos/";
        File directory = new File(directoryPath);
        if (!directory.exists()) {
            directory.mkdirs(); // 创建目录
        }
        String filePath = directoryPath + file.getOriginalFilename();
        File dest = new File(filePath);

        try {
            file.transferTo(dest);
            Photo photo = new Photo();
            photo.setUserId(userId);
            photo.setPhotoPath(filePath);
            photo.setCreatedAt(new Date());
            userPhotoRepository.save(photo);
            return "Photo uploaded successfully!";
        } catch (IOException e) {
            e.printStackTrace();
            return "Photo upload failed!";
        }
    }
}
